from rest_framework import serializers
from .utils import check_user_token
from django_redis import get_redis_connection
from users.models import User
from .models import OauthQQUser

class QQauthUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='用户认证')
    mobile = serializers.RegexField(label='手机号',regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码',min_length=8,max_length=20)
    sms_code = serializers.CharField(label='短信验证码',min_length=6,max_length=6)

    def validate(self, attrs):

        #获取认证凭据
        openid = check_user_token(attrs['access_token'])
        if openid is None:
            raise serializers.ValidationError('认证信息无效')

        #验证短信验证码
        redis = get_redis_connection('code')
        sms_redis = redis.get('sms_%s'%attrs['mobile'])
        if sms_redis is None:
            raise serializers.ValidationError('短信验证码已过期')
        if sms_redis.decode().lower() != attrs['sms_code'].lower():
            raise  serializers.ValidationError('短信验证码错误')

        #判断用户是否存在
        user = None
        try:
            user = User.objects.get(mobile = attrs['mobile'])
        except User.DoesNotExist:
            #1.不存在，创建用户
            pass
        else:
            #2.存在，验证密码
            bRet =user.check_password(attrs['password'])
            if not bRet:
                raise serializers.ValidationError('密码错误')

        attrs['openid'] =openid
        attrs['user'] = user

        return attrs

    def create(self, validated_data):

        user = validated_data['user']

        if user is None:
            user = User.objects.create_user(
                username=validated_data['mobile'],
                mobile = validated_data['mobile'],
                password = validated_data['password'],
            )

        OauthQQUser.objects.create(
            openid = validated_data['openid'],
            user = user
        )
        return user
